# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：商品部分的序列化器
"""
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, ListField
from goods.models import Category, Attr, Goods, GoodsAttr
import django_filters


class GoodsCategorySerializer(ModelSerializer):
    """
    商品分类序列化器
    """
    attrs_static_list = ListField(read_only=True)
    attrs_dynamic_list = ListField(read_only=True)

    class Meta:
        model = Category
        fields = '__all__'


class GoodsAttrSerializer(ModelSerializer):
    """
    商品属性序列化器
    """

    class Meta:
        model = Attr
        fields = '__all__'


class GoodsSerializer(ModelSerializer):
    """
    商品序列化器
    """
    big_log = serializers.ListField(required=False, allow_null=True, write_only=True)
    image_url = serializers.CharField(read_only=True)
    state = serializers.IntegerField(default=0)  # 0未通过 1审核中 2已审核
    is_promote = serializers.IntegerField(default=0)  # 0否 1是
    cid_one = serializers.IntegerField(write_only=True)
    cid_two = serializers.IntegerField(write_only=True)
    cid_three = serializers.IntegerField(write_only=True)

    category_one = serializers.CharField(read_only=True)
    category_two = serializers.CharField(read_only=True)
    category_three = serializers.CharField(read_only=True)

    dynamic_attrs = ListField(write_only=True)
    static_attrs = ListField(write_only=True)
    atts_list = serializers.ListField(read_only=True)

    class Meta:
        model = Goods
        fields = ['id', 'name', 'price', 'number', 'introduce', 'big_log', 'image_url', 'state', 'is_promote',
                  'hot_number', 'weight', 'cid_one', 'cid_two', 'cid_three', 'atts_list', 'category_one',
                  'category_two', 'category_three', 'dynamic_attrs', 'static_attrs']

    def validate(self, attrs):
        name = attrs.get('name', None)
        if Goods.objects.filter(name=name).exists():
            raise serializers.ValidationError('商品名称已存在!')
        state = attrs.get('state', None)
        if state not in [0, 1, 2]:
            raise serializers.ValidationError('商品状态不正确!')
        is_promote = attrs.get('is_promote', None)
        if is_promote not in [0, 1]:
            raise serializers.ValidationError('商品状态不正确!')
        cid_one = attrs.get('cid_one', None)
        if not Category.objects.filter(id=cid_one, level=1).exists():
            raise serializers.ValidationError('该一级分类不存在!')
        cid_two = attrs.get('cid_two', None)
        if not Category.objects.filter(id=cid_two, level=2, pid=cid_one).exists():
            raise serializers.ValidationError('该二级分类不存在!')
        cid_three = attrs.get('cid_three', None)
        if not Category.objects.filter(id=cid_three, level=3, pid=cid_two).exists():
            raise serializers.ValidationError('该二级分类不存在!')
        dynamic_attrs = attrs.get('dynamic_attrs', None)
        for dattr in dynamic_attrs:
            if not Attr.objects.filter(id=dattr, _type=1).exists():
                raise serializers.ValidationError('该动态属性不存在!')
        static_attrs = attrs.get('static_attrs', None)
        for sattr in static_attrs:
            if not Attr.objects.filter(id=sattr, _type=0).exists():
                raise serializers.ValidationError('该静态属性不存在!')
        return attrs

    def create(self, validated_data):
        cid_one = validated_data.pop('cid_one', None)
        cid_two = validated_data.pop('cid_two', None)
        cid_three = validated_data.pop('cid_three', None)
        dynamic_attrs = validated_data.pop('dynamic_attrs', None)
        static_attrs = validated_data.pop('static_attrs', None)
        big_log = validated_data.pop('big_log', None)
        if big_log:
            big_log_str = ",".join(big_log)
        else:
            big_log_str = ''
        good = Goods.objects.create(**validated_data, big_log=big_log_str, cid_one_id=cid_one, cid_two_id=cid_two,
                                    cid_three_id=cid_three)
        for dattr in dynamic_attrs:
            GoodsAttr.objects.create(gid=good, aid=Attr.objects.filter(id=dattr).first(),
                                     val=Attr.objects.filter(id=dattr).first().val, _type=1)
        for sattr in static_attrs:
            GoodsAttr.objects.create(gid=good, aid=Attr.objects.filter(id=sattr).first(),
                                     val=Attr.objects.filter(id=sattr).first().val, _type=0)
        return good


class GoodsImageSerializer(ModelSerializer):
    """
    商品图片序列化器
    """

    class Meta:
        model = Goods
        fields = ('big_log',)


# 自定义过滤器
class GoodsFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')
    atts = django_filters.CharFilter(field_name='atts__name', lookup_expr='icontains')

    class Meta:
        model = Goods
        fields = ('name', 'atts')
